﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using VSSAHT.DataAccess;
using VSSAHT.Transfer;
using CrystalDecisions;
using CrystalDecisions.CrystalReports.Engine;
using VSSAHT;
using Excel = Microsoft.Office.Interop.Excel;
using System.Linq;

namespace VSS_AHT.ReportForms
{
    public partial class FormReport : BaseForm
    {
        #region Singleton Members
        private static volatile FormReport instance;
        private static object syncRoot = new Object();

        public static FormReport Instance
        {
            get
            {
                lock (syncRoot)
                {
                    if (instance == null)
                        instance = new FormReport();
                }

                return instance;
            }
        }
        #endregion

        public FormReport()
        {
            InitializeComponent();

            // svc
            svc.AddService(typeof(IItemDataAccess), new ItemDataAccess());
            svc.AddService(typeof(ICustomerDataAccess), new CustomerDataAccess());
            svc.AddService(typeof(IScaleTicketDataAccess), new ScaleTicketDataAccess());
        }

        protected override void OnLoadData()
        {

            // Load scale type. Value 0 is Receives and value 1 is Invoices, value 2 is Transfer
            this.cboTicketType.Properties.Items.Add("NHẬP (PR)"); // Purchase Receive
            this.cboTicketType.Properties.Items.Add("XUẤT SỬ DỤNG (CI)"); // Consumer Invoice
            this.cboTicketType.Properties.Items.Add("XUẤT BÁN (SI)"); // Sales Invoice
            this.cboTicketType.Properties.Items.Add("CHUYỂN (NHẬP: TR)"); // Transfer
            this.cboTicketType.Properties.Items.Add("CHUYỂN (XUẤT: TI)"); // Transfer

            // Load Items List
            //var items = (svc.GetService(typeof(IItemDataAccess)) as IItemDataAccess).GetAll();
            //this.lookUpItemNumber.Properties.DataSource = items;
            //this.lookUpItemNumber.Properties.DisplayMember = "ItemNumber";
            //this.lookUpItemNumber.Properties.ValueMember = "ItemName";
            //this.lookUpItemNumber.Properties.SearchMode = DevExpress.XtraEditors.Controls.SearchMode.AutoComplete;
            // Load Items List
            var items = (svc.GetService(typeof(IItemDataAccess)) as IItemDataAccess).GetAll();
            foreach (var item in items)
            {
                this.lookUpItemNumber.Items.Add(new Femiani.Forms.UI.Input.AutoCompleteEntry(item.ItemName + ",  " + item.ItemNumber, item.ItemName, item.ItemName));
            }
            this.lookUpItemNumber.Tag = items;
            // Load Vendors List
            //var vendors = (svc.GetService(typeof(ICustomerDataAccess)) as ICustomerDataAccess).GetAll();
            //this.lookUpVendorNumber.Properties.DataSource = vendors;
            //this.lookUpVendorNumber.Properties.DisplayMember = "CustomerCode";
            //this.lookUpVendorNumber.Properties.ValueMember = "CustomerName";
            //this.lookUpVendorNumber.Properties.SearchMode = DevExpress.XtraEditors.Controls.SearchMode.AutoComplete;
            var vendors = (svc.GetService(typeof(ICustomerDataAccess)) as ICustomerDataAccess).GetAll();
            foreach (var vendor in vendors)
            {
                this.lookUpVendorNumber.Items.Add(new Femiani.Forms.UI.Input.AutoCompleteEntry(vendor.CustomerName + ",  " + vendor.CustomerCode, vendor.CustomerName, vendor.CustomerName));
            }
            this.lookUpVendorNumber.Tag = vendors;

            base.OnLoadData();
        }

        protected override void OnEvents()
        {
            this.btnClose.Click += new EventHandler(delegate { this.Close(); });
            this.Disposed += new EventHandler(delegate { instance = null; });
            this.btnView.Click += new EventHandler(btnView_Click);
            this.btnReset.Click +=new EventHandler(btnReset_Click);
            this.btnExcel.Click += new EventHandler(btnExcel_Click);
            //this.lookUpItemNumber.EditValueChanged += new EventHandler(lookUpItemNumber_EditValueChanged);
            //this.lookUpVendorNumber.EditValueChanged += new EventHandler(lookUpVendorNumber_EditValueChanged);

            this.lookUpItemNumber.TextChanged += new EventHandler(lookUpItemNumber_TextChanged);
            this.lookUpVendorNumber.TextChanged += new EventHandler(lookUpVendorNumber_TextChanged);
            base.OnEvents();
        }

        void lookUpVendorNumber_TextChanged(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(this.lookUpVendorNumber.Text))
            {
                IList<CustomerDTO> vendors = this.lookUpVendorNumber.Tag as IList<CustomerDTO>;
                if (vendors != null)
                {
                    var vendor = vendors.SingleOrDefault(x => x.CustomerName == this.lookUpVendorNumber.Text);
                    if (vendor != null)
                        this.txtVendorName.Text = vendor.CustomerCode;
                }
            }
            else
            {
                this.txtVendorName.Text = String.Empty;
            }
        }

        void lookUpItemNumber_TextChanged(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(this.lookUpItemNumber.Text))
            {
                IList<ItemDTO> items = this.lookUpItemNumber.Tag as IList<ItemDTO>;
                if (items != null)
                {
                    var item = items.SingleOrDefault(x => x.ItemName == this.lookUpItemNumber.Text);
                    if (item != null)
                    {
                        this.txtItemName.Text = item.ItemNumber;
                    }
                }
            }
            else
            {
                this.txtItemName.Text = String.Empty;
            }
        }

        protected void btnExcel_Click(object sender, EventArgs e)
        {
            IScaleTicketDataAccess daScaleTicket = svc.GetService(typeof(IScaleTicketDataAccess)) as IScaleTicketDataAccess;
            string vendorID = String.Empty;
            string itemID = String.Empty;
            string scaleType = String.Empty;
            string locationID = String.Empty;
            string requireCode = String.Empty;
            string vehicleID = String.Empty;
            string companyName = "CTY TNHH THÉP AN HƯNG TƯỜNG";
            string sdt = "BÀN CÂN 1(CBL) - 0650.3560706";

          //  vehicleID = txtVehicleNumber.Text;//get vehicle number

            if (!String.IsNullOrEmpty(this.txtItemName.Text))
                itemID = this.txtItemName.Text;
            if (!String.IsNullOrEmpty(this.txtVendorName.Text))
                vendorID = this.txtVendorName.Text;
            if (!String.IsNullOrEmpty(this.txtVehicleNumber.Text))
                vehicleID = this.txtVehicleNumber.Text;

            if (this.dateFrom.EditValue == null || this.dateTo.EditValue == null)
            {
                Common.ShowAlert("Bạn phải chọn đầy đủ phiếu cân từ ngày nào đến ngày nào");
            }
            else
            {
                if (this.cboTicketType.EditValue != null)
                {
                    switch (this.cboTicketType.SelectedIndex)
                    {
                        case 0:
                            scaleType = "PR";
                            break;
                        case 1:
                            scaleType = "CI";
                            break;
                        case 2:
                            scaleType = "SI";
                            break;
                        case 3:
                            // Receive
                            scaleType = "TR";
                            break;
                        case 4:
                            scaleType = "TI";
                            break;
                    }
                }
                DateTime inTime = dateFrom.DateTime;
                TimeSpan ti = new TimeSpan(0, 0, 0);
                inTime = inTime.Date + ti;
                DateTime outTime = this.dateTo.DateTime;
                TimeSpan to = new TimeSpan(23, 59, 59);
                outTime = outTime.Date + to;
                
                IList<ScaleTicketDTO> list = daScaleTicket.GetList(inTime, outTime, scaleType, itemID, vendorID, locationID, requireCode, vehicleID);
                ILocationDataAccess locationDA = new LocationDataAccess();
                IList<LocationDTO> _locationList = locationDA.GetAll();
               // var location = locationDA.Get(ticket.LocationCode);
                //if (location != null)
                //    ticket.LocationName = location.LocationName;

                foreach(ScaleTicketDTO ticket in list )
                 {
                     foreach (LocationDTO location in _locationList)
                     {
                         if (ticket.LocationCode.Equals(location.LocationCode))
                         {
                             ticket.LocationName = location.LocationName;
                             break;
                         }
                     }
                 }

                IList<TitleClass> titles = new List<TitleClass>();
                List<HeaderClass> headers = new List<HeaderClass>();
                if((list!=null) && list.Count>0)
                {
                    switch ((short)radioGroup1.EditValue)
                    {
                        case 0:
                            titles.Add(new TitleClass()
                            {
                                Row = 4,
                                Col = 0,
                                Bold = true,
                                Text = "BÁO CÁO THEO NGÀY",
                                Size = 14,
                                Merge = true,
                                Align = Excel.Constants.xlCenter
                            });

                            headers.AddRange(new HeaderClass[] 
                            {
                        new HeaderClass() { Text = "Mã phiếu", DataMember="ScaleTicketCode" },
                        new HeaderClass() { Text = "Số xe", DataMember="VehicleID" },                        
                        new HeaderClass() { Text = "Khách hàng", DataMember="CustomerName" },
                        new HeaderClass() { Text = "Hàng hóa", DataMember="ItemName" },
                        new HeaderClass() { Text = "Kho", DataMember="LocationName" },
                        new HeaderClass() { Text = "Ngày giờ vào", DataMember="InHour" },
                        new HeaderClass() { Text = "Ngày giờ ra", DataMember="OutHour" },
                        new HeaderClass() { Text = "Lần cân 1", DataMember="FirstWeight" },
                        new HeaderClass() { Text = "Lần cân 2", DataMember="SecondWeight" },                       
                        new HeaderClass() { Text = "TL Hàng", DataMember="ActualWeight" },
                        new HeaderClass() { Text = "Số Kg trừ", DataMember="KgReduce" },
                        new HeaderClass() { Text = "Số % trừ", DataMember="PercentReduce" },
                        new HeaderClass() { Text = "Số lượng 1", DataMember="Quantity1" },
                        new HeaderClass() { Text = "ĐVT 1", DataMember="ItemUnit" },
                        new HeaderClass() { Text = "Số lượng 2", DataMember="Quantity2" },
                        new HeaderClass() { Text = "ĐVT 2", DataMember="ItemUnit2" },
                        new HeaderClass() { Text = "Tỉ trọng", DataMember="Rate" },
                        new HeaderClass() { Text = "Số cây", DataMember="SoCay" },
                        new HeaderClass() { Text = "Diễn giải", DataMember="Description" },

                            });
                            break;
                        case 1:
                            titles.Add(new TitleClass()
                            {
                                Row = 4,
                                Col = 0,
                                Bold = true,
                                Text = "BÁO CÁO THEO HÀNG HÓA",
                                Size = 14,
                                Merge = true,
                                Align = Excel.Constants.xlCenter
                            });

                            headers.AddRange(new HeaderClass[] 
                            {
                        new HeaderClass() { Text = "Mã phiếu", DataMember="ScaleTicketCode" },
                        new HeaderClass() { Text = "Số xe", DataMember="VehicleID" },                        
                        new HeaderClass() { Text = "Khách hàng", DataMember="CustomerName" },
                        new HeaderClass() { Text = "Hàng hóa", DataMember="ItemName" },
                        new HeaderClass() { Text = "Kho", DataMember="LocationName" },
                        new HeaderClass() { Text = "Ngày giờ vào", DataMember="InHour" },
                        new HeaderClass() { Text = "Ngày giờ ra", DataMember="OutHour" },
                        new HeaderClass() { Text = "Lần cân 1", DataMember="FirstWeight" },
                        new HeaderClass() { Text = "Lần cân 2", DataMember="SecondWeight" },                       
                        new HeaderClass() { Text = "TL Hàng", DataMember="ActualWeight" },
                        new HeaderClass() { Text = "Số Kg trừ", DataMember="KgReduce" },
                        new HeaderClass() { Text = "Số % trừ", DataMember="PercentReduce" },
                        new HeaderClass() { Text = "Số lượng 1", DataMember="Quantity1" },
                        new HeaderClass() { Text = "ĐVT 1", DataMember="ItemUnit" },
                        new HeaderClass() { Text = "Số lượng 2", DataMember="Quantity2" },
                        new HeaderClass() { Text = "ĐVT 2", DataMember="ItemUnit2" },
                        new HeaderClass() { Text = "Đơn trọng", DataMember="Rate" },
                        new HeaderClass() { Text = "Số cây", DataMember="SoCay" },
                        new HeaderClass() { Text = "Diễn giải", DataMember="Description" },

                            });
                            break;
                        case 2:
                            titles.Add(new TitleClass()
                            {
                                Row = 4,
                                Col = 0,
                                Bold = true,
                                Text = "BÁO CÁO THEO KHÁCH HÀNG",
                                Size = 14,
                                Merge = true,
                                Align = Excel.Constants.xlCenter
                            });

                            headers.AddRange(new HeaderClass[] 
                            {
                        new HeaderClass() { Text = "Mã phiếu", DataMember="ScaleTicketCode" },
                        new HeaderClass() { Text = "Số xe", DataMember="VehicleID" },                        
                        new HeaderClass() { Text = "Khách hàng", DataMember="CustomerName" },
                        new HeaderClass() { Text = "Hàng hóa", DataMember="ItemName" },
                        new HeaderClass() { Text = "Kho", DataMember="LocationName" },
                        new HeaderClass() { Text = "Ngày giờ vào", DataMember="InHour" },
                        new HeaderClass() { Text = "Ngày giờ ra", DataMember="OutHour" },
                        new HeaderClass() { Text = "Lần cân 1", DataMember="FirstWeight" },
                        new HeaderClass() { Text = "Lần cân 2", DataMember="SecondWeight" },                       
                        new HeaderClass() { Text = "TL Hàng", DataMember="ActualWeight" },
                        new HeaderClass() { Text = "Số Kg trừ", DataMember="KgReduce" },
                        new HeaderClass() { Text = "Số % trừ", DataMember="PercentReduce" },
                        new HeaderClass() { Text = "Số lượng 1", DataMember="Quantity1" },
                        new HeaderClass() { Text = "ĐVT 1", DataMember="ItemUnit" },
                        new HeaderClass() { Text = "Số lượng 2", DataMember="Quantity2" },
                        new HeaderClass() { Text = "ĐVT 2", DataMember="ItemUnit2" },
                        new HeaderClass() { Text = "Đơn trọng", DataMember="Rate" },
                        new HeaderClass() { Text = "Số cây", DataMember="SoCay" },
                        new HeaderClass() { Text = "Diễn giải", DataMember="Description" },

                            });
                            break;
                        case 3:
                            titles.Add(new TitleClass()
                            {
                                Row = 4,
                                Col = 0,
                                Bold = true,
                                Text = "BÁO CÁO THEO SỐ XE",
                                Size = 14,
                                Merge = true,
                                Align = Excel.Constants.xlCenter
                            });

                            headers.AddRange(new HeaderClass[] 
                            {
                        new HeaderClass() { Text = "Mã phiếu", DataMember="ScaleTicketCode" },
                        new HeaderClass() { Text = "Số xe", DataMember="VehicleID" },                        
                        new HeaderClass() { Text = "Khách hàng", DataMember="CustomerName" },
                        new HeaderClass() { Text = "Hàng hóa", DataMember="ItemName" },
                        new HeaderClass() { Text = "Kho", DataMember="LocationName" },
                        new HeaderClass() { Text = "Ngày giờ vào", DataMember="InHour" },
                        new HeaderClass() { Text = "Ngày giờ ra", DataMember="OutHour" },
                        new HeaderClass() { Text = "Lần cân 1", DataMember="FirstWeight" },
                        new HeaderClass() { Text = "Lần cân 2", DataMember="SecondWeight" },                       
                        new HeaderClass() { Text = "TL Hàng", DataMember="ActualWeight" },
                        new HeaderClass() { Text = "Số Kg trừ", DataMember="KgReduce" },
                        new HeaderClass() { Text = "Số % trừ", DataMember="PercentReduce" },
                        new HeaderClass() { Text = "Số lượng 1", DataMember="Quantity1" },
                        new HeaderClass() { Text = "ĐVT 1", DataMember="ItemUnit" },
                        new HeaderClass() { Text = "Số lượng 2", DataMember="Quantity2" },
                        new HeaderClass() { Text = "ĐVT 2", DataMember="ItemUnit2" },
                        new HeaderClass() { Text = "Đơn trọng", DataMember="Rate" },
                        new HeaderClass() { Text = "Số cây", DataMember="SoCay" },
                        new HeaderClass() { Text = "Diễn giải", DataMember="Description" },

                            });
                            break;
                    }

                    DataTable dataTable = CollectionExtensions<ScaleTicketDTO>.ConvertToDataTable(list, "VSSTQH_ScaleDTO");
                    titles.Add(new TitleClass() { Row = 1, Col = 0, Bold = false, Text = companyName, Size = 10 });
                    titles.Add(new TitleClass() { Row = 2, Col = 0, Bold = false, Text = sdt, Size = 10 });
                    string fromToDate = String.Format("Từ {0:d}  Đến {1:d} {1:HH:mm}", this.dateFrom.DateTime, this.dateTo.DateTime);
                    titles.Add(new TitleClass() { Row = 5, Col = 6, Bold = false, Text = fromToDate, Size = 10 });
                    string vendorName = "Khách hàng: " + (this.lookUpVendorNumber.Text == "" ? "Không xác định" : this.lookUpVendorNumber.Text);
                    titles.Add(new TitleClass() { Row = 6, Col = 5, Bold = false, Text = vendorName, Size = 10 });
                    string productName = "Hàng hóa: " + (this.lookUpItemNumber.Text == "" ? "Không xác định" : this.lookUpItemNumber.Text);
                    titles.Add(new TitleClass() { Row = 6, Col = 7, Bold = false, Text = productName, Size = 10 });
                    string vID = "Số xe: " + (String.IsNullOrEmpty(vehicleID) ? "Không xác định" : vehicleID);
                    titles.Add(new TitleClass() { Row = 7, Col = 5, Bold = false, Text = vID, Size = 10 });
                    string typeWeight = "Kiểu cân: " + (scaleType == "" ? "Không xác định" : scaleType);
                    titles.Add(new TitleClass() { Row = 7, Col = 7, Bold = false, Text = vID, Size = 10 });

                    if (ReportDB.exportDataToExcel(titles, headers, dataTable))
                    {
                        MessageBox.Show("Đã lưu Excel thành công.", "Thông báo");
                    }
                    else
                    {
                        Common.ShowAlert("Xuất Excel thất bại");
                    }
                }
            }
        }

        /// <summary>
        /// Look up vendor number
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //protected void lookUpVendorNumber_EditValueChanged(object sender, EventArgs e)
        //{
        //    if (this.lookUpVendorNumber.EditValue != null)
        //    {
        //        this.txtVendorName.Text = this.lookUpVendorNumber.EditValue.ToString();
        //    }
        //    else
        //    {
        //        this.txtVendorName.Text = String.Empty;
        //    }
        //}

        /// <summary>
        /// Look up item number
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //protected void lookUpItemNumber_EditValueChanged(object sender, EventArgs e)
        //{
        //    if (this.lookUpItemNumber.EditValue != null)
        //    {
        //        this.txtItemName.Text = this.lookUpItemNumber.EditValue.ToString();
        //    }
        //    else
        //    {
        //        this.txtItemName.Text = String.Empty;
        //    }
        //}

        private void btnReset_Click(object sender, EventArgs e)
        {
            this.lookUpItemNumber.Text = String.Empty;
            this.lookUpVendorNumber.Text =String.Empty;
            this.txtItemName.Text = String.Empty;
            this.txtVendorName.Text = String.Empty;
            this.cboTicketType.EditValue = null;
            this.txtVehicleNumber.Text = String.Empty;
        }

        protected void btnView_Click(object sender, EventArgs e)
        {
            IScaleTicketDataAccess daScaleTicket = svc.GetService(typeof(IScaleTicketDataAccess)) as IScaleTicketDataAccess;
            string vendorID = String.Empty;
            string itemID = String.Empty;
            string scaleType = String.Empty;
            string locationID = String.Empty;
            string requireCode = String.Empty;
            string vehicleID = String.Empty;

            if (!String.IsNullOrEmpty(this.txtItemName.Text))
                itemID = this.txtItemName.Text;
            if (!String.IsNullOrEmpty(this.txtVendorName.Text))
                vendorID = this.txtVendorName.Text;
            if (!String.IsNullOrEmpty(this.txtVehicleNumber.Text))
                vehicleID = this.txtVehicleNumber.Text;

            if (this.dateFrom.EditValue == null || this.dateTo.EditValue == null)
            {
                Common.ShowAlert("Bạn phải chọn đầy đủ phiếu cân từ ngày nào đến ngày nào");
            }
            else
            {
                if (this.cboTicketType.EditValue != null)
                {
                    switch (this.cboTicketType.SelectedIndex)
                    {
                        case 0:
                            scaleType = "PR";
                            break;
                        case 1:
                            scaleType = "CI";
                            break;
                        case 2:
                            scaleType = "SI";
                            break;
                        case 3:
                                                            // Receive
                                scaleType = "TR";
                                break;
                        case 4:
                                scaleType = "TI";
                            break;
                    }
                }
                DateTime inTime = dateFrom.DateTime;
                TimeSpan ti = new TimeSpan(0, 0, 0);
                inTime = inTime.Date + ti;
                DateTime outTime = this.dateTo.DateTime;
                TimeSpan to = new TimeSpan(23, 59, 59);
                outTime = outTime.Date + to;
                IList<ScaleTicketDTO> list = daScaleTicket.GetList(inTime, outTime, scaleType, itemID, vendorID, locationID, requireCode, vehicleID);

                if (list != null && list.Count > 0)
                {
                    ReportDocument report = new ReportDocument();
                    report.PrintOptions.PaperOrientation = CrystalDecisions.Shared.PaperOrientation.Landscape;
                    switch ((short)radioGroup1.EditValue)
                    {
                        case 0:
                            // Date
                            report.Load(Application.StartupPath + "/Reports/rptDateScale.rpt");
                            break;
                        case 1:
                            // Item
                            report.Load(Application.StartupPath + "/Reports/rptItemNameScale.rpt");
                            break;
                        case 2:
                            // Customer
                            report.Load(Application.StartupPath + "/Reports/rptCustomerScale.rpt");
                            break;
                        case 3:
                            // VehicleScale
                            report.Load(Application.StartupPath + "/Reports/rptVehicleScale.rpt");
                            break;
                        case 4:
                            // Summary
                            report.Load(Application.StartupPath + "/Reports/rptSummary.rpt");
                            break;
                    }

                    if (report != null)
                    {
                        report.SetDataSource(CollectionExtensions<ScaleTicketDTO>.ConvertToDataTable(list, "ScaleTicket"));

                        report.SetParameterValue("FromDate", String.Format("{0:d} {0:HH:mm}", inTime));
                        report.SetParameterValue("ToDate", String.Format("{0:d} {0:HH:mm}", this.dateTo.DateTime));
                        report.SetParameterValue("VendorName", this.lookUpVendorNumber.Text == "" ? "Không xác định" : this.lookUpVendorNumber.Text);
                        report.SetParameterValue("ProductName", this.lookUpItemNumber.Text == "" ? "Không xác định" : this.lookUpItemNumber.Text);
                        report.SetParameterValue("VehicleID", String.IsNullOrEmpty(vehicleID) ? "Không xác định" : vehicleID);
                        report.SetParameterValue("WeightType", this.cboTicketType.EditValue == null ? "Tất cả loại cân" : cboTicketType.Text);

                        SettingApp setting = new SettingApp();
                        
                        if (Common.CheckPrinter(setting.ReportPrintName))
                            report.PrintOptions.PrinterName = setting.ReportPrintName;
                        if (setting.IsPreviewReportPrint)
                        {
                            FormPrintPreview form = new FormPrintPreview(report);
                            form.ShowDialog();
                        }
                        else
                        {
                            report.PrintToPrinter(1, false, 0, 0);
                        }
                    }
                }
                else
                {
                    Common.ShowAlert("Từ {0:d} {0:HH:mm} Đến {1:d} {1:HH:mm} không có cân xe!", dateFrom.DateTime, dateTo.DateTime);
                }
            }
        }
    }
}